package com.ydd.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ydd.constant.MessageConstant;
import com.ydd.context.BaseContext;
import com.ydd.dto.IndexSetTopPage;
import com.ydd.dto.ListDTO;
import com.ydd.dto.RegDTO;
import com.ydd.entity.*;
import com.ydd.mapper.*;
import com.ydd.result.Result;
import com.ydd.service.HomePageService;
import com.ydd.utils.JwtUtil;
import com.ydd.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import javax.crypto.SecretKey;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class HomePageServiceImpl implements HomePageService {


    @Autowired
    private YddCateMapper yddCateMapper;
    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private YddTagMapper yddTagMapper;
    @Autowired
    private YddLinkMapper yddLinkMapper;
    @Autowired
    private YddAdvimgMapper yddAdvimgMapper;
    @Autowired
    private YddAdvposMapper yddAdvposlMapper;



    @Autowired
    private HomePageMapper homePageMapper;

    /**
     * 热门文章置顶
     *
     * @param setTopPage
     * @return
     */
    @Override
    public Result setTop(IndexSetTopPage setTopPage) {
        // 判断是否为空
        if (setTopPage.getPage() == null) {
            setTopPage.setPage("1");
        }
        if (setTopPage.getLimit() == null) {
            setTopPage.setLimit("10");
        }

        // 当前的秒值
        long nowTime = System.currentTimeMillis()/1000;
        int num = 24*60*60;
        // 一天的秒值
        long dayTime = nowTime - num;
        // 一周的秒值
        long weekdayTime = nowTime - num*7;

        // 执行分页
        Integer start = Integer.valueOf(setTopPage.getPage());
        Integer limit = Integer.valueOf(setTopPage.getLimit());
        PageHelper.startPage(start,limit);
        // 条件查询
        Page<YddArticle> pageSearch = homePageMapper.searchYddArticle(null);
        // 总条数及集合
        Integer total = Math.toIntExact(pageSearch.getTotal()); // 总条数
        int pages = pageSearch.getPages();  // 总页数
        List<YddArticle> yddArticleList = pageSearch.getResult();


        // 一天的更新
        int dayCount = 0;
        // 一周的更新
        int weekCount = 0;
        List<PageHome> pageHomes = new ArrayList<>();
        for (YddArticle yddArticle : yddArticleList) {
            PageHome pageHome = new PageHome();
            BeanUtils.copyProperties(yddArticle, pageHome);
            // 时间
            String time = (yddArticle.getCreateDate()+"").substring(0,10);
            Integer integerTime = Integer.valueOf(time);
            if(integerTime >= dayTime){
                dayCount++;
            }
            if (integerTime >= weekCount){
                weekdayTime++;
            }
            pageHome.setCreate_date(integerTime);
            // 根据cate_id查询分类
            Integer cateId = yddArticle.getCateid();
            YddCate yddCate = homePageMapper.searchCateName(cateId);
            // pageHome的cateName赋值
            pageHome.setCatename(yddCate.getCatename());
            // 添加到列表
            pageHomes.add(pageHome);
        }


        PageHomeList pageHomeList = new PageHomeList();
        pageHomeList.setPageSize(Integer.valueOf(setTopPage.getLimit()));
        pageHomeList.setCurrentPage(Integer.valueOf(setTopPage.getPage()));
        pageHomeList.setCount(total);
        pageHomeList.setTotalPages(pages);
        pageHomeList.setData(pageHomes);


        // 创建返回的实体类
        PageHomeVO pageHomeVO = new PageHomeVO();

        pageHomeVO.setDesc("热门文章置顶");

        pageHomeVO.setNum_day(dayCount);
        pageHomeVO.setNum_week(weekCount);

        pageHomeVO.setList(pageHomeList);

        // 返回数据
        return Result.success(pageHomeVO);
    }

    /**
     * 文章列表数据
     *
     * @param listDTO
     * @return
     */
    @Override
    public Result listArticle(ListDTO listDTO) {
        // 判断是否为空
        if (listDTO.getPage() == null) {
            listDTO.setPage("1");
        }
        if (listDTO.getLimit() == null) {
            listDTO.setLimit("10");
        }
        // 执行分页
        PageHelper.startPage(Integer.valueOf(listDTO.getPage()),Integer.valueOf(listDTO.getLimit()));
        // 条件查询
        Page<YddArticle> pageSearch = homePageMapper.searchYddArticle(listDTO.getCateid());
        // 总条数及集合
        Integer total = Math.toIntExact(pageSearch.getTotal()); // 总条数
        int pages = pageSearch.getPages();  // 总页数
        List<YddArticle> yddArticleList = pageSearch.getResult();
        List<PageHome> pageHomes = new ArrayList<>();
        for (YddArticle yddArticle : yddArticleList) {
            PageHome pageHome = new PageHome();
            BeanUtils.copyProperties(yddArticle, pageHome);
            // 根据分类id查询分类
            Integer cateId = yddArticle.getCateid();
            YddCate yddCate = homePageMapper.searchCateName(cateId);
            // pageHome的cateName赋值
            pageHome.setCatename(yddCate.getCatename());
            // 添加到列表
            pageHomes.add(pageHome);
        }


        // 返回数据
        PageHomeArticleListVO pageHomeArticleListVO = new PageHomeArticleListVO();

        PageHomeArticleList pageHomeList = new PageHomeArticleList();
        pageHomeList.setPageSize(Integer.valueOf(listDTO.getLimit()));
        pageHomeList.setCurrentPage(Integer.valueOf(listDTO.getPage()));
        pageHomeList.setCount(total);
        pageHomeList.setTotalPages(pages);
        pageHomeList.setData(pageHomes);
        pageHomeArticleListVO.setList(pageHomeList);

        return Result.success(pageHomeArticleListVO);
    }

    /**
     * 注册
     *
     * @param regDTO
     * @return
     */
    @Override
    public Result regUser(RegDTO regDTO) {
        // 判断非空
        if(regDTO.getMobile() == null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        if (regDTO.getPassword() == null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }

        SysUser sysUser = new SysUser();
        UUID uuid = UUID.randomUUID();

        sysUser.setId(uuid.toString());
        sysUser.setPhone(regDTO.getMobile()+"");
        sysUser.setPassword(regDTO.getPassword());
        sysUser.setCreateDate(LocalDateTime.now());
        sysUser.setUpdateDate(LocalDateTime.now());
        sysUser.setLoginIp(BaseContext.getCurrentId()+"");
        sysUser.setLoginName("");
        sysUser.setDelFlag("0");
        sysUser.setEmail("");
        sysUser.setRoleId("");
        sysUser.setDefaultData("1");
        sysUser.setStatus(1);
        sysUser.setName(BaseContext.getCurrentId()+"");

        homePageMapper.addUser(sysUser);

        RegUserInfo userInfo = new RegUserInfo();
        BeanUtils.copyProperties(sysUser,userInfo);

        // 返回数据
        RegDataVO regDataVO = new RegDataVO();
        regDataVO.setUserInfo(userInfo);
        regDataVO.setCollectNum(0);
        regDataVO.setArticleNum(0);
        regDataVO.setZanNum(0);
        // 得道token秘钥
        SecretKey secretKey = JwtUtil.generalKey();
        regDataVO.setToken(secretKey.toString());

        return Result.success(regDataVO);
    }

    /**
     * 最新文章
     *
     * @return
     */
    @Override
    public Result hotArticle() {
        List<YddArticle> yddArticleList = homePageMapper.searchYddArticleAll();

        List<HotArticle> hotArticleList = new ArrayList<>();
        for (YddArticle yddArticle : yddArticleList) {

            HotArticle hotArticle = new HotArticle();
            BeanUtils.copyProperties(yddArticle,hotArticle);

            YddCate yddCate = homePageMapper.searchCateName(yddArticle.getCateid());
            hotArticle.setCatename(yddCate.getCatename());
            hotArticleList.add(hotArticle);
        }
        HotVO data = new HotVO();
        data.setDesc("最新文章");
        data.setList(hotArticleList);
        return Result.success(data);
    }

    /**
     * 推荐文章
     *
     * @return
     */
    @Override
    public Result recommend() {
        List<YddArticle> yddArticleList = homePageMapper.searchYddArticleAll();

        List<Recommend> recommendList = new ArrayList<>();
        for (YddArticle yddArticle : yddArticleList) {
            Recommend recommend = new Recommend();
            BeanUtils.copyProperties(yddArticle, recommend);
            // 根据cateId查询catename
            YddCate yddCate = homePageMapper.searchCateName(yddArticle.getCateid());
            String cateName = yddCate.getCatename();
            // 将cateName存到recommend里面
            recommend.setCatename(cateName);
            recommendList.add(recommend);
        }
        // 返回数据
        RecommendVO recommendVO = new RecommendVO();
        recommendVO.setList(recommendList);
        recommendVO.setDesc("返回推荐文章");
        return Result.success(recommendVO);
    }


    /**
     * 文章详情数据
     *
     * @param id
     * @return
     */
    @Override
    public Result showArticleDetail(String id) {
        // 判断是否为空
        if (id == null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        Integer intId = Integer.valueOf(id);
        Integer prevId = intId - 1;
        Integer nextId = intId + 1;

        // 传进来id的数据
        YddArticle yddArticle = homePageMapper.searchById(id);
        InfoArticle infoArticle = new InfoArticle();
        BeanUtils.copyProperties(yddArticle, infoArticle);
        String infoArticleTime = (yddArticle.getCreateDate()+"").substring(0,10);
        infoArticle.setCreate_date(Integer.valueOf(infoArticleTime));

        // 前一个id
        YddArticle preYddArticle = homePageMapper.searchById(String.valueOf(prevId));
        PrevArticle prevArticle = new PrevArticle();
        BeanUtils.copyProperties(preYddArticle, prevArticle);
        String preYddArticleTime = (preYddArticle.getCreateDate()+"").substring(0,10);
        infoArticle.setCreate_date(Integer.valueOf(preYddArticleTime));

        // 下一个id
        YddArticle nextYddArticle = homePageMapper.searchById(String.valueOf(nextId));
        NextArticle nextArticle = new NextArticle();
        BeanUtils.copyProperties(nextYddArticle, nextArticle);
        String nextYddArticleTime = (nextYddArticle.getCreateDate()+"").substring(0,10);
        infoArticle.setCreate_date(Integer.valueOf(nextYddArticleTime));

        // 返回数据
        ArticleDetailVO data = new ArticleDetailVO();
        data.setInfo(infoArticle);
        data.setPrev(prevArticle);
        data.setNext(nextArticle);

        return Result.success(data);
    }

    /**
     * 首页和全局数据
     *
     * @return
     */
    @Override
    public Result<IYddArticleDataVO> index() {
        List<YddCate> cateList = yddCateMapper.yddcateList();
        ArrayList<YddCate> yddCates = new ArrayList<>();
        cateList.forEach(yddCate -> {
            YddCate cate = new YddCate();
            BeanUtils.copyProperties(yddCate,cate);
            yddCates.add(cate);
        });
        List<SysConfig> sysconList = sysConfigMapper.sysconList();
        List<SysConfig> sysConfigList = new ArrayList<>();
        sysconList.forEach(sysConfig -> {
            SysConfig config = new SysConfig();
            BeanUtils.copyProperties(sysConfig,config);
            sysConfigList.add(config);
        });
        List<YddTag> tagList = yddTagMapper.yddTagList();
        ArrayList<YddTag> yddTags = new ArrayList<>();
        tagList.forEach(yddTag -> {
            YddTag tag = new YddTag();
            BeanUtils.copyProperties(yddCates,tag);
            yddTags.add(tag);
        });
        List<YddLink> yddList = yddLinkMapper.yddList();
        ArrayList<YddLink> arrayList = new ArrayList<>();
        yddList.forEach(yddLink -> {
            YddLink link = new YddLink();
            BeanUtils.copyProperties(yddLink,link);
            arrayList.add(link);
        });
        List<Integer> integerList = yddAdvposlMapper.adbposList();
        ArrayList<YddAdvimg> arrayListBan = new ArrayList<>();
        ArrayList<YddAdvimg> arrayListSid = new ArrayList<>();
        ArrayList<YddAdvimg> arrayListSho= new ArrayList<>();
        for (Integer integer : integerList) {
            if (integer==15){
                List<YddAdvimg> yddAdvimgList = yddAdvimgMapper.yddList(String.valueOf(integer));
                yddAdvimgList.forEach(yddAdvimg -> {
                    arrayListBan.add(yddAdvimg);
                });
            }else if (integer==14 || integer==15){
                List<YddAdvimg> yddAdvimgSid = yddAdvimgMapper.yddList(String.valueOf(integer));
                yddAdvimgSid.forEach(yddAdvimg -> {
                    arrayListSid.add(yddAdvimg);
                });
            }else if (integer==12 ||integer==13){
                List<YddAdvimg> yddAdvimgSho = yddAdvimgMapper.yddList(String.valueOf(integer));
                yddAdvimgSho.forEach(yddAdvimg -> {
                    arrayListSho.add(yddAdvimg);
                });

            }else if (integer==null){
                break;
            }
        }
        List<IYddArticleList> list = new ArrayList<>();
        list.forEach(iYddArticleList -> {
            IYddArticleList iYddArticleList1 = new IYddArticleList();
            iYddArticleList.setList(sysConfigList);
            list.add(iYddArticleList1);
        });

        IYddArticleDataVO vo = new IYddArticleDataVO();
        vo.setAllCate(yddCates);
        vo.setConfig(list);
        vo.setAllTag(yddTags);
        vo.setAllLink(arrayList);
        vo.setBanner(arrayListBan);
        vo.setSideBanner(arrayListSid);
        vo.setShowBanner(arrayListSho);
        return Result.success(vo);
    }
}
